package impl;

import anaydis.sort.SorterType;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class QuickSorterCutOff extends QuickSorterNonRecursive{

    final int M;
    public QuickSorterCutOff(int M){
        super(SorterType.QUICK_CUT);
        this.M = M;
    }

    public <T> void sort(Comparator<T> tComparator, List<T> ts){
        List<Integer> pivotes = new ArrayList<Integer>();
        pivotes.add(0);
        pivotes.add(ts.size());
        int i = 0;
        while((i*2)+1<pivotes.size()){
            if(Math.abs(pivotes.get((2*i)+1) - pivotes.get(2*i)) > M){
                int g = partition(tComparator, ts, pivotes.get(2*i) , pivotes.get((2*i)+1), (pivotes.get((2*i)+1))-1);
                pivotes.add(pivotes.get(2*i));
                pivotes.add(g);
                pivotes.add(g);
                pivotes.add(pivotes.get((2*i)+1));
            }
            else{
                (new InsertionSorter()).sort(tComparator, ts, pivotes.get(2*i), pivotes.get((2*i)+1));
            }
            i++;
        }
    }


    /*partition ubica el pivote en su posicion final, y a todos los mayores
    *a el a la derecha y los menores o iguales a izquierda.
    *Return indice final del pivote
    */

    @NotNull
    public SorterType getType(){
        return SorterType.QUICK_CUT;
    }
}
